<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../lib/index.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        canvas{
            margin: 50px auto 0;
            display: block;
            background: yellow;
        }
    </style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
<script>
    let ctx = document.getElementById('canvas');
    // 获取webgl上下文
    let gl = ctx.getContext('webgl')
    // 顶点着色器
    let VERTEX_SHADER_SOURCE = `
        attribute vec4 aPosition;
        void main(){
            gl_Position = aPosition;
            gl_PointSize = 30.0;
        }
    `;
    // 片元着色器
    const FRAGMENT_SHADER_SOURCE = `
        void main(){
            gl_FragColor = vec4(1.0, 0.0, 0.1, 1.0);
        }
    `;
    let program = initShader(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE)
    // 获取 attribute变量，必须在initShader之后
    let aPosition = gl.getAttribLocation(program, 'aPosition')

    let points = []
    // webgl 没法监听点击事件，所以我们绑定在canvasshang
    ctx.onclick = function (ev) {
        // 坐标
        let x = ev.clientX;
        let y = ev.clientY;

        // ctx.offsetTop
        // ctx.offsetLeft

        let domPosition = ev.target.getBoundingClientRect();
        // console.log(domPosition,ctx.offsetTop,ctx.offsetLeft);

        // canvas坐标
        let domx = x - domPosition.left;
        let domy = y - domPosition.top;

        // 水平方向：需要先减去 当前画布的宽度一半，再除以话不得宽度一半
        // 垂直方向：让画布高度一半 减去，在除以画布高度一半
        /*
        水平:
        0 200 400 变为  -1 0 1
        先减去200
        -200 0 200
        再除以200
        -1 0 1

        垂直:
        0 200 400 变为  1 0 -1
        200减去它
        200 0 -200
        再除以200
        1 0 -1
        */

        let halfWidth = ctx.offsetWidth / 2
        let halfHeight = ctx.offsetHeight / 2

        // webgl坐标
        let clickX = (domx - halfWidth) / halfWidth
        let clickY = (halfHeight - domy) / halfHeight
        // console.log(clickX, clickY)

        points.push({clickX, clickY})
        for (let i=0;i<points.length;i++){
            // 使用点击的坐标 绘制点
            // 赋值
            gl.vertexAttrib2f(aPosition, points[i].clickX, points[i].clickY)
            // 执行绘制
            gl.drawArrays(gl.POINTS, 0, 1);
        }

    }
</script>
</html>
